const { query } = require("./db.js");

class UserDao {
    // 登录的数据库操作
    async loginUser(account, pwd) {
        try {
            const rows = await query("SELECT * FROM user WHERE user_account = ? AND user_pwd = ?", [account, pwd]);
            return rows[0];
        } catch (err) {
            console.error("Error logging in user:", err);
            throw err;
        }
    }

    // 修改密码
    async updateUserPwd(account, oldPwd, newPwd) {
        try {
            // 先检查用户是否存在并验证旧密码是否正确
            const rows = await query("SELECT * FROM user WHERE user_account = ? AND user_pwd = ?", [account, oldPwd]);
            if (rows.length === 0) {
                throw new Error("用户不存在或旧密码错误");
            }

            // 更新用户的密码
            await query("UPDATE user SET user_pwd = ? WHERE user_account = ?", [newPwd, account]);

            // 返回成功标志
            return true;
        } catch (err) {
            console.error("Error updating password:", err);
            throw err;
        }
    }
}

module.exports = new UserDao();